package com.walkingfiles.registry

import org.springframework.dao.DataIntegrityViolationException

class FileController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
    }

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [fileInstanceList: File.list(params), fileInstanceTotal: File.count()]
    }

	def create() {
		def documentInstance = null
		def fileInstanceList = null
		if (params.documentId) {
			documentInstance = Document.get(params.documentId)
			fileInstanceList = File.findAllByDocument(documentInstance, [sort: "dateCreated", order: "desc"])
		}
		[fileInstance: new File(params),
		 documentInstance: documentInstance,
		 fileInstanceList: fileInstanceList]
	}

	def save() {
		def fileInstance = new File(params)
		if (params.data) {
			if (!params.data.getOriginalFilename() || 
				!params.data.getSize()) {
				fileInstance.errors.rejectValue("data", "file.emptyFile.message", "The file cannot be empty")
				render(view: "create", model: [fileInstance: fileInstance])
				return
			}
		}
        if (!fileInstance.save(flush: true)) {
            render(view: "create", model: [fileInstance: fileInstance])
            return
        }
        def username = authenticatedUser.username
        LogItem.fileAttached(fileInstance, username)
		flash.message = message(code: 'default.created.message', args: [message(code: 'file.label', default: 'File'), fileInstance.id])
		// redirect(controller: 'Document',action: "show", id: params['document.id'])
		redirect(action: "create", params: [documentId: params['document.id']])
    }
    def show() {
        def fileInstance = File.get(params.id)
        if (!fileInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'file.label', default: 'File'), params.id])
            redirect(action: "list")
            return
        }

        [fileInstance: fileInstance]
    }
    
    def download() {
        def fileInstance = File.get(params.id)
        if (!fileInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'file.label', default: 'File'), params.id])
            redirect(action: "list")
            return
        }
        response.setContentType("application/octet-stream")
        response.setHeader("Content-disposition", "attachment;filename=${fileInstance.name}.${fileInstance.type.name}")
        response.outputStream << fileInstance.data // Performing a binary stream copy
        
    }

    def edit() {
        def fileInstance = File.get(params.id)
        if (!fileInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'file.label', default: 'File'), params.id])
            redirect(action: "list")
            return
        }

        [fileInstance: fileInstance]
    }

    def update() {
        def fileInstance = File.get(params.id)
        if (!fileInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'file.label', default: 'File'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (fileInstance.version > version) {
                fileInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'file.label', default: 'File')] as Object[],
                          "Another user has updated this File while you were editing")
                render(view: "edit", model: [fileInstance: fileInstance])
                return
            }
        }

        fileInstance.properties = params

        if (!fileInstance.save(flush: true)) {
            render(view: "edit", model: [fileInstance: fileInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'file.label', default: 'File'), fileInstance.id])
        redirect(action: "show", id: fileInstance.id)
    }

    def delete() {
        def fileInstance = File.get(params.id)
        if (!fileInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'file.label', default: 'File'), params.id])
            redirect(action: "list")
            return
        }

        try {
            fileInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'file.label', default: 'File'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'file.label', default: 'File'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
